<?php
namespace app\admin\controller;
use think\Db;

use think\Controller;
/**
 * 平台信息控制器
 */
class Index extends Common {
	private $db = null;
	private $config = '';
	private $default_config = '';
	private $oto_db_prefix = ''; //oto平台数据库名和表前缀
	private $pt_table_prefix = ''; //跑腿平台表前缀
	private $userField = '';
	protected function _initialize(){
		parent::_initialize();
		$this->config = config('database.db_config');
		$this->default_config = config('database');
		$this->oto_db_prefix = $this->config['database'].'.'.$this->config['prefix'];
		$this->pt_table_prefix = config('database.prefix');
		$this->db = Db::connect($this->config);
	}

	/**
	 * [index 首页主页信息]
	 * @return [type] [description]
	 */
	public function index(){
		$weekInfo = $this->getWeekInfo();
		$sumInfo = $this->getSumInfo();
		$this->assign('weekInfo',$weekInfo);
		$this->assign('sumInfo',$sumInfo);
		return $this->fetch();
	}

	/**
	 * 一周动态
	 * @return [type] [description]
	 */
	public function getWeekInfo(){
		$m = $this->db;
		$ret = array();
		//用户
		$weekDate = date('Y-m-d 00:00:00',time()-604800);//一周内
		$ret['userNew'] = $m->name('users')->where('userFlag=1 and createTime>"'.$weekDate.'"')->count();//新增用户
		
		//申请店铺
		$ret['shopApply'] = $m->name('shops')->where('shopStatus >= 0 and shopFlag=1 and createTime>"'.$weekDate.'"')->count();
		
		//新增商品
		$ret['goodsNew'] = $m->name('goods')->where('goodsFlag=1 and createTime>"'.$weekDate.'"')->count();
		//新增订单 - 唐峰康改 
		// $ret['ordersNew'] = $m->name('orders')->where('orderFlag=1 and orderStatus >=0 and createTime>"'.$weekDate.'"')->count();
		$weekDateTimestamp = time()-604800;
		$ret['ordersNew'] = db('send_order')->where('pay_status=1 and time>"'.$weekDateTimestamp.'"')->count();
		//新增店铺
		$map['shopStatus'] = 1;
		$ret['shopNew'] = $m->name('shops')->where('shopStatus = 1 and shopFlag=1 and createTime>"'.$weekDate.'"')->count();
		return $ret;
	}

	/**
	 * 统计信息
	 * @return array 统计信息的数组
	 */
	public function getSumInfo(){
		$m = $this->db;
		$ret = array();
		$ret['userSum'] = $m->name('users')->where('userFlag=1')->count();//新增用户
		//申请店铺
		$ret['shopApplySum'] = $m->name('shops')->where('shopStatus = 0 and shopFlag=1')->count();
		//商品
		$ret['goodsSum'] = $m->name('goods')->where('goodsFlag=1')->count();
		// 唐峰康 改
		//订单
		$ret['ordersSum'] = db('send_order')->where('pay_status = 1')->count();
		//订单总金额
		$ret['moneySum'] = db('send_order')->where('pay_status = 1')->sum('money');
		
		//店铺
		$ret['shopSum'] = $m->name('shops')->where('shopStatus = 1 and shopFlag=1')->count();
		return $ret;
	}
	
	/**
	 * [tomallconfig 平台信息]
	 * @return [type] [description]
	 */
	public function tomallconfig(){
		$m = $this->db->name('sys_configs');
		$sql = "select * from ".$this->oto_db_prefix."sys_configs where fieldType != 'hidden' order by parentId asc,fieldSort asc";
		$rs = $m->query($sql);
		foreach ($rs as $key => $value) {
			if($value['fieldType']=='other'){
				$sql = "select * from ".$this->oto_db_prefix."sys_configs where fieldCode='defaultCity'";
				$data = $m->query($sql);
				$city = $this->db->name('areas')->where('areaId='.$data[0]['fieldValue'])->find();
				$province = $this->db->name('areas')->where('areaId='.$city['parentId'])->find();
				$rs[$key]['city']=$city['areaName'];
				$rs[$key]['province']=$province['areaName'];
				$rs[$key]['provinceId']=$province['areaId'];
				$cityList = $this->db->name('areas')->where('parentId='.$city['parentId'])->select();
				$this->assign('city',$cityList);
			}
		}
		$list =  $this->getChildList($rs);
		$child = array();
		foreach ($list as $key => $value) {
			if(!empty($value['child'])){
				array_push($child,$list[$key]['child']);
			}
		}
		$sql1 = "select * from ".$this->oto_db_prefix."sys_configs where fieldType='upload' order by parentId asc,fieldSort asc";
		$upload = $m->query($sql1);
		$province = $this->db->name('areas')->where('areaFlag=1 and isShow = 1 and parentId=0')->select();
		$cityList = $this->db->name('areas')->where('areaFlag=1 and isShow = 1 and parentId=0')->select();
		$this->assign('province',$province);		
		$this->assign('upload',$upload);		
		$this->assign('list',$list);
		$this->assign('child',$child);
		return $this->fetch('edit');
	}

	/**
	 * [edit 修改平台信息]
	 * @return [json] [description]
	 */
	public function edit(){
		$pars = $this->request->param();
		// dump($pars);
		// exit();
		$params = array();
		foreach ($pars as $key => $value) {
			$params[$key]=$value;
		}
		$files = request()->file();
		if(!empty($files)){
			foreach ($files as $key => $value) {
				$picurl = $this->user_upload($key);
				$params = array_merge($params,$picurl);
			}
		}
		// print_r($params);
		$m = $this->db->name('sys_configs');
		$sql = "select * from ".$this->oto_db_prefix."sys_configs where fieldType!='hidden' order by parentId asc,fieldSort asc";
		$data = $m->query($sql);
		$status = true;
		//要更新的字段数组
		$updates = array();
		foreach($params as $key=>$value){
			array_push($updates,$key);
		}
		if(!empty($data)){
			foreach ($data as $key => $v){
				if(in_array($v['fieldCode'], $updates)){
					$res = $m-> where('fieldCode="'.$v['fieldCode'].'"')->setField('fieldValue',$params[$v['fieldCode']]);
					if($res === false){
						$status = false;
						break;
					}
				}
			}
			if($status){
				$result = array('code' => 1,'reload' => 1,'url' => url('index/tomallconfig'),'msg' => '修改成功');
			}else{
				$result = array('code' => 0,'reload' => 0,'url' => url('index/tomallconfig'),'msg' => '修改失败');
			}
		}
		return json($result);
	}


	/**
	  * [getChildList 获取菜单树]
	  * @param  [type]  $cate     [description]
	  * @param  integer $parentId [description]
	  * @param  integer $level    [description]
	  * @return [type]            [description]
	  */
	 protected function getChildList($cate,$parentId=0,$level=0){
	 	$arr = array();
	 	foreach ($cate as $k => $v) {
			if ($v['parentId'] == $parentId) {
				$v['level'] = $level + 1;
				$v['child'] = self::getChildList($cate,$v['configId'],$level + 1);
				array_push($arr,$v);
			}
		}
		return $arr;
	 }

	 /**
	 * [user_upload 上传图片]
	 * @return [array] [description]
	 */
	private function user_upload($file){
		$adFile = '';
		$adFile = request()->file($file);
		// 移动到框架应用根目录/public/uploads/ 目录下
		if ($adFile){
			$info = $adFile->move(ROOT_PATH . DS . config('uplaod') .DS.'face');
			if ($info){
				$adFile = config('uplaod').'/face/'.str_replace('\\', '/', $info->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$data[$file] = $adFile;
		return $data;
	}

	/**
	 * [getCity 获取城市列表]
	 * @return [json] [ajax请求]
	 */
	public function getCity(){
		if (!request()->isAjax()) $this->error('操作失败');
		$m = $this->db->name('areas');
		$data = $m->where(array('parentId' => input('pid'),'areaType'=>1,'isShow'=>1))->select();
		$html = '';
		// 1省，2市，3区
		foreach ($data as $key => $value){
			$html .= '<option value="'.$value['areaId'].'">'.$value['areaName'].'</option>';
		}
		$result = ['status'=>1,'html'=>$html];
		return json($result);
	}
	
}